<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {Dialog} from "@/components/Dialog";
import {studentImport} from "@/api/student";
import {useCommon} from "@/hooks/web/useCommon";
import UploadDefault from "@/components/uploadFile/UploadDefault.vue";
import {ElMessage} from "element-plus";

let {getProjectTree, projectTree} = useCommon();

const props = defineProps({
  excelVisible: Boolean,
})
const emit = defineEmits(['handleClose'])

let loading = ref(false)
let excelRef = ref('')
let file = ref('')
const importForm = reactive({
  school_id: '',
  type: 'student'
})

const handleExcelCancel = () => {
  excelRef.value.resetFields()
  emit('handleClose')
}
const onSave = () => {
  excelRef.value.validate(async valid => {
    if (valid) {
      if (!file.value.fileList.length) return ElMessage({type: 'warning', message: '请上传文件'})
      let data = {
        school_id: importForm.school_id,
        type: importForm.type,
        file_id: file.value.fileList[0].fileId
      }
      console.log(data);
      loading.value = true
      let res = await studentImport(data);
      loading.value = false
      console.log(res);

      if (res) {
        ElMessage({type: 'success', message: '导入成功'});
        handleExcelCancel()
      }
    }
  })
}

defineExpose({importForm})
onMounted(() => {
  getProjectTree()
})
</script>

<template>
  <Dialog :title="'Excel批量导入'" :model-value="excelVisible" @handle-close="handleExcelCancel" :max-height="'200px'">
    <el-row>
      <el-form :model="importForm" ref="excelRef" label-width="120px">
        <el-col :span="24">
          <el-form-item label="选择学校/项目" prop="school_id"
                        :rules="[{required: true,message: '请选择学校/项目',trigger: 'change'} ]"
          >
            <el-cascader
                clearable
                style="width: 275px"
                v-model="importForm.school_id"
                :options="projectTree"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="上传文件" required>
            <upload-default :file-type="'text'" ref="file"></upload-default>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <template v-slot:footer>
      <el-button @click="handleExcelCancel">取 消</el-button>
      <el-button type="primary" @click="onSave" :loading="loading">确认导入</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="less">

</style>